﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

public partial class Pages_RawMaterialOrder : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        this.Form.Attributes.Add("novalidate", "");

        if (!IsPostBack)
        {
            handleEditMode();
            bindSupplier();
            BindPaymentTerms();
            BindShippingTerms();
            bindShipping();
            bindCurrency();

        }
    }

    #region Bind Payment Terms
    private void BindPaymentTerms()
    {
        BLL_tbl_purchase_order bll = new BLL_tbl_purchase_order();
        try
        {
            DataTable dt = bll.GetPaymentTerms();
            ddlPAYMENT_TERM_ID.DataSource = dt;
            ddlPAYMENT_TERM_ID.DataTextField = dt.Columns["PAYMENT_TERM"].ToString();
            ddlPAYMENT_TERM_ID.DataValueField = dt.Columns["PAYMENT_TERM_ID"].ToString();
            ddlPAYMENT_TERM_ID.DataBind();
            ddlPAYMENT_TERM_ID.Items.Insert(0, "--Select Payment Term--");
            return;
        }
        catch (Exception)
        {

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('Error Occured while fetching Client Details');", true);
            return;
        }
        finally
        {
            bll = null;

        }
    }

    #endregion

    #region Shipping Terms
    private void BindShippingTerms()
    {
        BLL_tbl_purchase_order bll = new BLL_tbl_purchase_order();
        try
        {
            DataTable dt = bll.GetShippingTerms();
            ddlSHIPPING_TERMS_ID.DataSource = dt;
            ddlSHIPPING_TERMS_ID.DataTextField = dt.Columns["SHIPPING_TERMS"].ToString();
            ddlSHIPPING_TERMS_ID.DataValueField = dt.Columns["SHIPPING_TERMS_ID"].ToString();
            ddlSHIPPING_TERMS_ID.DataBind();
            ddlSHIPPING_TERMS_ID.Items.Insert(0, "--Select Shipping Term--");
            return;
        }
        catch (Exception)
        {

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('Error Occured while fetching Client Details');", true);
            return;
        }
        finally
        {
            bll = null;

        }
    }

    #endregion

    #region Fetch Supplier Details and Supplier Dropdown

    private void bindSupplier()
    {
        BLL_tbl_raw_material_order bll = new BLL_tbl_raw_material_order();
        DataTable dt =  bll.fetchSuppliers();
        try
        {
            ddlSupplier_Name.DataSource = dt;
            ddlSupplier_Name.DataTextField = dt.Columns["supplier_Name"].ToString();
            ddlSupplier_Name.DataValueField = dt.Columns["user_code"].ToString();
            ddlSupplier_Name.DataBind();
            ddlSupplier_Name.Items.Insert(0, "--Select Supplier--");
        }
        finally
        {
            dt = null;
            bll = null;
        }
       
    }
    #endregion

    #region Fetch Shipping Type and Bind Shipping Dropdown
    private void bindShipping()
    {
        BLL_tbl_vessel_master bll = new BLL_tbl_vessel_master();
        try
        {
            ddl_Shipping_Type.DataSource = bll.selectAll();
            ddl_Shipping_Type.DataTextField = "VESSEL_TYPE";
            ddl_Shipping_Type.DataValueField = "VESSEL_ID";
            ddl_Shipping_Type.DataBind();
            ListItem li = new ListItem("--Select Shipping Type--", "0");
            ddl_Shipping_Type.Items.Insert(0, li);
        }
       finally
        {

            bll = null;
        }
      
    }
    #endregion

    #region Fetch and Bind Currency 

    private void bindCurrency()
    {
        BLL_tbl_currency_master bll = new BLL_tbl_currency_master();
        try
        {
            ddlCurrency.DataSource = bll.selectAll();
            ddlCurrency.DataTextField = "CURRENCY_NAME";
            ddlCurrency.DataValueField = "CURRENCY_ID";
            ddlCurrency.DataBind();
            ddlCurrency.Items.Insert(0, "--Select Currency--");
        }
        finally
        {

            bll = null;
        }
    }

    #endregion 

    #region Validate Form

    private string ValidateForm()
    {
        

        try
        {
            if (txtRM_ORDER_NUMBER.Text == "")
            {
                return "Invalid RM Number";
            }

            // Check if Supplier Selected 
            if (ddlSupplier_Name.SelectedIndex <= 0)
            {
                return "Please select Supplier Name";
            }

            // Check if Shipping type is selected 
            if (ddlPAYMENT_TERM_ID.SelectedIndex <= 0)
            {
                return "Please select Payment Terms";
            }

            if (ddlSHIPPING_TERMS_ID.SelectedIndex <= 0)
            {
                return "Please select shipping Terms";
            }

            // Check if Currency is Selected
            if (ddlCurrency.SelectedIndex <= 0)
            {
                return "Please select Currency";
            }

            // Check if price is Valid 
            if (txtPrice.Text == "")
            {
                return "Please Enter Price";
            }

           

            // Check if Quantity is entered 
            if (txtQuantity.Text == "")
            {
                return "Please Enter Quantity";
            }


            if (trUpload.Style["display"] == "")
            {
                //Check if Certificate is selected
                if (!fuploadCertification.HasFile)
                {
                    return "Please select Certificate File";
                }

                // Check if Certificate date is valid

                if (txtCERTIFICATION_DATE.Text == "")
                {
                    return "Please select Ceretificate Date";
                }
            }

            if (trUpload2.Style["display"] == "")
            {
                //Check if Certificate is selected
                if (!fuploadAgreement.HasFile)
                {
                    return "Please select Agreement File";
                }
            }
           

            // Check valid etd
            if (txtETD.Text == "")
            {
                return "Please select etd";
            }
           

            // Check valid eta
            if (txtETA.Text == "")
            {
                return "Please select eta";
            }
           


            // Check valid ets
            if (txtETS.Text == "")
            {
                return "Please select ets";
            }
           

            // Check if Shipping Details are entered 

            if (txtShippingDetails.Text == "")
            {
                return "Please enter Shipping Details";
            }

            return "";
        }
        catch (Exception ex)
        {

            return ex.Message.ToString();
        }

        

    }

    #endregion

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string formerror = ValidateForm();
        string fileName = "";
        string AgreementfileName="";
        if (trUpload.Style["display"] == "")
        {
            try
            {
                fileName = Guid.NewGuid().ToString() + Path.GetExtension(fuploadCertification.FileName);
                AgreementfileName = Guid.NewGuid().ToString() + Path.GetExtension(fuploadAgreement.FileName);
                string filePathToUpload = Server.MapPath("~/AllFiles/RawMaterialCertificates/" + fileName);
                fuploadCertification.SaveAs(filePathToUpload);
                string agreementfilePathToUpload = Server.MapPath("~/AllFiles/SupplierAgreement/" + AgreementfileName);
                fuploadCertification.SaveAs(agreementfilePathToUpload);
                BLL_tbl_supplier_master_Certificate bll_c = new BLL_tbl_supplier_master_Certificate();
                bll_c.update(ddlSupplier_Name.SelectedValue, fileName, fuploadCertification.FileName, txtCERTIFICATION_DATE.Text.toDateTimeWithoutError(),
                    User.Identity.Name, DateTime.Now, AgreementfileName, fuploadAgreement.FileName);
            }
            catch { }
        }

        if (formerror != "")
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('" + formerror + "');", true);
            return;
        }
        if (btnSave.CommandArgument == "")
        {
            tbl_raw_material_order model = new tbl_raw_material_order();
            model.RM_ORDER_NUMBER = txtRM_ORDER_NUMBER.Text.Trim();
            model.USER_CODE = ddlSupplier_Name.SelectedValue.ToString();
            model.CURRENCY_ID = Int32.Parse(ddlCurrency.SelectedValue.ToString());
            model.QUANTITY = Convert.ToInt32(txtQuantity.Text);
            model.Price = Convert.ToDecimal(txtPrice.Text.Trim());
            model.ETD = txtETD.Text.Trim().toDateTimeWithoutError();
            model.ETA = txtETA.Text.Trim().toDateTimeWithoutError();
            model.ETS = txtETS.Text.Trim().toDateTimeWithoutError();
            model.CERTIFICATION_DATE = txtCERTIFICATION_DATE.Text.toDateTimeWithoutError();
            model.VESSEL_ID = Convert.ToInt32(ddl_Shipping_Type.SelectedValue.Trim());
          model.ShippingDetails = txtShippingDetails.Text.Trim();
          model.IS_ACTIVE = true;
            model.CREATED_BY = User.Identity.Name;
            model.CREATED_DATE = DateTime.Now;
            model.PaymentTerms = ddlPAYMENT_TERM_ID.SelectedValue.Trim();
            model.ShippingTerms = ddlSHIPPING_TERMS_ID.SelectedValue.Trim();


            BLL_tbl_raw_material_order bll = new BLL_tbl_raw_material_order();
            bll.insert(model);
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success", "alert('Record Saved Succesfully');", true);
        }
        else
        {
            tbl_raw_material_order model = new tbl_raw_material_order();
            model.USER_CODE = ddlSupplier_Name.SelectedValue;
            model.VESSEL_ID =Convert.ToInt32(ddl_Shipping_Type.SelectedValue);
            model.Price = Convert.ToDecimal(txtPrice.Text.Trim());
            model.CURRENCY_ID =Convert.ToInt32(ddlCurrency.SelectedValue);
            model.CERTIFICATION_DATE = txtCERTIFICATION_DATE.Text.Trim().toDateTimeWithoutError();
            model.ShippingDetails = txtShippingDetails.Text.Trim();

            model.RAW_ORDER_ID = Convert.ToInt32(btnSave.CommandArgument);
            model.RM_ORDER_NUMBER = txtRM_ORDER_NUMBER.Text.Trim();
            model.QUANTITY = Convert.ToInt32(txtQuantity.Text);
            model.ETD = txtETD.Text.Trim().toDateTimeWithoutError();
            model.ETA = txtETA.Text.Trim().toDateTimeWithoutError();
            model.ETS = txtETS.Text.Trim().toDateTimeWithoutError();
            model.UPDATED_BY = User.Identity.Name;
            model.UPDATED_DATE = DateTime.Now;

            model.PaymentTerms = ddlPAYMENT_TERM_ID.SelectedValue.Trim();
            model.ShippingTerms =ddlSHIPPING_TERMS_ID.SelectedValue.Trim();

            BLL_tbl_raw_material_order bll = new BLL_tbl_raw_material_order();
            bll.update(model);
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success", "alert('Record Saved Succesfully');", true);
            btnSave.CommandArgument = "";
            Response.Redirect(Request.Url.AbsolutePath);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.Url.AbsolutePath);
    }

    protected void linkDelete_Click(object sender, EventArgs e)
    {
        string id = ((LinkButton)sender).CommandArgument;
        tbl_raw_material_order model = new tbl_raw_material_order();
        model.RAW_ORDER_ID = Convert.ToInt32(id); ;

        BLL_tbl_raw_material_order bll = new BLL_tbl_raw_material_order();
        bll.delete(model);
    }

    protected void linkEdit_Click(object sender, EventArgs e)
    {
        string id = ((LinkButton)sender).CommandArgument;
        Response.Redirect(Request.Url.AbsolutePath + "?editRecord=" + id);
    }
    
    protected void handleEditMode()
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["editRecord"] != null)
            {
                string id = Request.QueryString["editRecord"];
                BLL_tbl_raw_material_order bll = new BLL_tbl_raw_material_order();
                List<tbl_raw_material_order> list = bll.select(Convert.ToInt32(id));
                foreach (tbl_raw_material_order tbl in list)
                {
                    btnSave.CommandArgument = tbl.RAW_ORDER_ID.ToString();
                    bindSupplier();
                    ddlSupplier_Name.SelectedValue = tbl.USER_CODE;
                    ddlSupplier_Name_SelectedIndexChanged(null, null);
                    txtShippingDetails.Text = tbl.ShippingDetails;
                    txtRM_ORDER_NUMBER.Text = tbl.RM_ORDER_NUMBER;
                    ddl_Shipping_Type.SelectedValue = tbl.VESSEL_ID.ToString();
                    txtPrice.Text = tbl.Price.ToString();
                    ddlCurrency.SelectedValue = tbl.CURRENCY_ID.ToString();
                    txtQuantity.Text = tbl.QUANTITY.ToString();
                    txtETD.Text = tbl.ETD.ToString("yyyy-MM-dd");
                    txtETA.Text = tbl.ETA.ToString("yyyy-MM-dd");
                    txtETS.Text = tbl.ETS.ToString("yyyy-MM-dd");

                    ddlPAYMENT_TERM_ID.SelectedValue  = tbl.PaymentTerms;
                    ddlSHIPPING_TERMS_ID.SelectedValue = tbl.ShippingTerms;
                }
            }
        }
    }


    #region Supplier Name Selection Changed
    protected void ddlSupplier_Name_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlSupplier_Name.SelectedIndex <= 0)
        {
            txtSupplierCode.Text = "";
            txtSupplierAddress.Text = "";
            txtSupplierContact.Text = "";
            txtSupplierEmail.Text = "";
        }
        else
        {
            BLL_tbl_raw_material_order bll = new BLL_tbl_raw_material_order();
            DataTable dt = bll.fetchSuppliers();
            if (dt != null)
            {
                DataRow[] dr = dt.Select("user_code='" + ddlSupplier_Name.SelectedValue.ToString() + "'");
                if (dr.Length > 0)
                {
                    txtSupplierCode.Text = dr[0]["user_code"].ToString();
                    txtSupplierAddress.Text = dr[0]["Address"].ToString();
                    txtSupplierContact.Text = dr[0]["Contact"].ToString();
                    txtSupplierEmail.Text = dr[0]["Supplier_Email_id"].ToString();
                    txtRM_ORDER_NUMBER.Text = DateTime.Now.ToString("yyMMdd") + "-" + dr[0]["user_code"].ToString();
                }
            }
        }


        BLL_tbl_supplier_master_Certificate bll_c = new BLL_tbl_supplier_master_Certificate();
        List<tbl_supplier_master_Certificate> list_c = bll_c.select(txtSupplierCode.Text);
        if (list_c.Count > 0)
        {
            if (list_c[0].CERTIFICATION_FILE.Length > 0)
            {
                trUpload.Style.Add("display", "none");
                trCertificate.Style.Add("display", "");
                lblDownloadCertificate.Text = string.Format("<a target='_blank' href='../AllFiles/RawMaterialCertificates/{0}'>{1}</a>", list_c[0].CERTIFICATION_FILE, list_c[0].CERTIFICATION_FILE_ORIGINAL_NAME);
                txtCERTIFICATION_DATE.Attributes.Remove("type");
                txtCERTIFICATION_DATE.Attributes.Add("type", "text");
                txtCERTIFICATION_DATE.Text = list_c[0].CERTIFICATION_DATE.ToString("MM/dd/yyyy");
                txtCERTIFICATION_DATE.Enabled = false;

                trUpload2.Style.Add("display", "none");
                trAgreement.Style.Add("display", "");
                lblDownloadAgreement.Text = string.Format("<a target='_blank' href='../AllFiles/SupplierAgreement/{0}'>{1}</a>", list_c[0].Supplier_Agreement, list_c[0].Supplier_Agreement_Original_Name);
            }
            else
            {
                trUpload.Style.Add("display", "");
                trCertificate.Style.Add("display", "none");
                txtCERTIFICATION_DATE.Enabled = true;
                txtCERTIFICATION_DATE.Attributes.Remove("type");
                txtCERTIFICATION_DATE.Attributes.Add("type", "date");
                //txtRM_ORDER_NUMBER.Text = "";

                trUpload2.Style.Add("display", "");
                trAgreement.Style.Add("display", "none");
            }
        }
        else
        {
            trUpload.Style.Add("display", "");
            trCertificate.Style.Add("display", "none");
            txtCERTIFICATION_DATE.Enabled = true;
            txtCERTIFICATION_DATE.Attributes.Remove("type");
            txtCERTIFICATION_DATE.Attributes.Add("type", "date");
            //txtRM_ORDER_NUMBER.Text = "";

            trUpload2.Style.Add("display", "");
            trAgreement.Style.Add("display", "none");
        }

    }
    #endregion
}